package com.mrd.gtimp.sup.service;

import com.mrd.base.BaseBiz;
import com.mrd.constant.BaseTypeConstant;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.sup.entity.SupCustomer;
import com.mrd.gtimp.sup.entity.SupCustomerRole;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.result.SupAddBatchResult;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Service
public class SupCustomerBiz extends BaseBiz<SupCustomer> {

    @Resource
    private SupCustomerRoleBiz supCustomerRoleBiz;
    @Resource
    private CompanyBiz companyBiz;


    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("supCustomerDao")
    public void setBaseRepository(BaseRepository<SupCustomer, String> baseRepository) {
        super.baseRepository = baseRepository;
    }


    public SupAddBatchResult addBatch(String[] idArr, String toComId, String creator)
            throws Exception {
        SupAddBatchResult result = new SupAddBatchResult();
        if (idArr != null && idArr.length > 0) {
            StringBuffer sb = new StringBuffer();
            for (String string : idArr) {
                sb.append(string).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            Filter filters = new Filter();
            filters.setGroupOp(FilterGroupOption.AND);
            filters.addRule(new SearchRule("company.id", SearchRuleOption.in, sb.toString()));
            filters.addRule(new SearchRule("COM_ID", SearchRuleOption.eq, toComId));
            int counts = baseRepository.findEntityCount(filters);

            List<String> idList = new ArrayList<String>();
            for (String id : idArr) {
                idList.add(id);
            }

            if (counts > 0) {
                List<SupCustomer> exsitDatas = baseRepository.findEntityByFilter(0, counts, filters, null);
                for (SupCustomer cus : exsitDatas) {
                    idList.remove(cus.getCompany().getId());
                }
                result.setMessage("其中" + counts + "条记录已存在您的客户关系列表中。");
            }
            // save
            SupCustomerRole defaultRole = supCustomerRoleBiz.getDefaultCustomerRole(toComId);
            for (String aid : idList) {
                Company company = new Company();
                company.setId(aid);

                SupCustomer supCustomer = new SupCustomer();
                supCustomer.setCREATOR(creator);
                supCustomer.setCTIME(new Date());
                supCustomer.setID(null);
                supCustomer.setCustomerRole(defaultRole);

                supCustomer.setCOM_ID(toComId);
                supCustomer.setCompany(company);
                baseRepository.saveOrupdate(supCustomer);
            }
            result.setSuccessCount(idList.size());
            result.setFailCount(counts);
        } else {
            result.setMessage("no data");
        }
        return result;
    }

    public SupCustomerRoleBiz getSupCustomerRoleBiz() {
        return supCustomerRoleBiz;
    }

    public void setSupCustomerRoleBiz(SupCustomerRoleBiz supCustomerRoleBiz) {
        this.supCustomerRoleBiz = supCustomerRoleBiz;
    }

    /**
     * 获取指定用户的供应商，如果是超级管理员则获取所有供应商，如果自己是供应商则供应商列表包含自己
     */

    public String getSelfSupCompanyStr(User user) {
        StringBuffer supIds = new StringBuffer();
        try {
            if (user.isAdmin()) {
                Filter filter = new Filter();
                filter.addRule(new SearchRule("type", SearchRuleOption.eq, BaseTypeConstant.COMPANY_TYPE_SUP));
                List<Company> companys = companyBiz.findEntityByFilter(0, 0, filter, null);
                for (Company company : companys) {
                    supIds.append(company.getId()).append(",");
                }
                if (supIds.charAt(supIds.length() - 1) == ',') {
                    supIds.deleteCharAt(supIds.length() - 1);
                }
            } else {
                List<SupCustomer> sup = null;
                Filter filter = new Filter();
                filter.addRule(new SearchRule("company.id", SearchRuleOption.eq, user.getCompany()
                        .getId()));
                sup = this.findEntityByFilter(0, 0, filter, null);
                if (sup != null && sup.size() != 0) {
                    for (SupCustomer supCustomer : sup) {
                        supIds.append(supCustomer.getCOM_ID()).append(",");
                    }
                    if (user.getCompany().getType().equals(BaseTypeConstant.COMPANY_TYPE_SUP)) {
                        supIds.append(user.getCompany().getId());
                    }
                    if (supIds.charAt(supIds.length() - 1) == ',') {
                        supIds.deleteCharAt(supIds.length() - 1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return supIds.toString();
    }
}
